#include "Controller.h"
#include "KeyManager.h"
#include "ContactsManager.h"
#include "SelectionManager.h"
#include "EncryptionOperationsManager.h"
#include "KeyOperationsManager.h"
#include "Contact.h"
#include "Group.h"
#include "SymmetricKeyInfo.h"
#include "KeyInfo.h"

using namespace kryptos::selection;
using namespace kryptos::cryptography;
using namespace kryptos::util;
using namespace kryptos::entities;

namespace kryptos { namespace controller {

Controller::Controller()
{
    init();
}

Controller::~Controller()
{
}

Controller& Controller::instance()
{
    static Controller instance;
    return instance;
}


void Controller::init()
{
    qRegisterMetaType<kryptos::entities::Contact>("Contact");
    qRegisterMetaType<kryptos::entities::ContactList>("ContactList");
    qRegisterMetaType<kryptos::entities::Group>("Group");
    qRegisterMetaType<kryptos::entities::GroupList>("GroupList");
    qRegisterMetaType<kryptos::entities::KeyInfo>("KeyInfo");
    qRegisterMetaType<kryptos::entities::KeyInfoList>("KeyInfoList");
    qRegisterMetaType<kryptos::entities::SymmetricKeyInfo>("SymmetricKeyInfo");
    qRegisterMetaType<kryptos::entities::SymmetricKeyInfoList>("SymmetricKeyInfoList");

    m_appActive = false;
    m_shorcut.setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Space));

    connect(&m_shorcut, SIGNAL(activated()), this, SLOT(shortcutActivated()));

    connect(&EncryptionOperationsManager::manager(), SIGNAL(passphraseNeeded(const kryptos::entities::KeyInfo&)), this, SLOT(getPassphraseForKey(const kryptos::entities::KeyInfo&)));
    connect(&EncryptionOperationsManager::manager(), SIGNAL(wrongPassphrase(kryptos::entities::KeyInfo)), this, SLOT(getPassphraseForKeyAgain(const kryptos::entities::KeyInfo&)));
    //connect(&EncryptionOperationsManager::manager(), SIGNAL(encryptionOperationStarted()), this, SIGNAL());
    connect(&EncryptionOperationsManager::manager(), SIGNAL(encryptionOperationEnded()), this, SIGNAL(encryptionOperationFinished()));

    connect(&KeyOperationsManager::manager(), SIGNAL(keyOperationEnded()), this, SIGNAL(keyOperationFinished()));
}

void Controller::viewIsReady()
{
    if (!SelectionManager::initialized())
        SelectionManager::manager("Kryptos");
}

void Controller::getPassphraseForKey(const KeyInfo& keyinfo)
{
    emit passphraseNeeded(keyinfo.name(), keyinfo.email());
}

void Controller::getPassphraseForKeyAgain(const KeyInfo& keyinfo)
{
    emit wrongPassphrase(keyinfo.name(), keyinfo.email());
}

void Controller::passphraseFromUserReady(const std::string& passphrase)
{
    emit passphraseReady(passphrase);
}

void Controller::shortcutActivated()
{
    m_appActive ? emit hideApplication()
                : emit showApplication();

    m_appActive = !m_appActive;
}

GroupList Controller::contacts()
{
    return ContactsManager::manager().allGroups();
}

}}
